package org.hbbTlias2025.service.IMPL;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.hbbTlias2025.mapper.ClassMapper;
import org.hbbTlias2025.mapper.StudentMapper;
//import org.example.hbbproject010303.pojo.*;
import org.hbbTlias2025.pojo.ClassQueryParam;
import org.hbbTlias2025.pojo.Clazz;
import org.hbbTlias2025.pojo.pageReturn;
import org.hbbTlias2025.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClassMapper classMapper;

    @Autowired
    private StudentMapper studentMapper;

    public pageReturn<Clazz> findAllClass(ClassQueryParam classQueryParam) {

        try {
            PageHelper.startPage(classQueryParam.getPage(), classQueryParam.getPageSize());

            //2. 执行查询
            List<Clazz> classList = classMapper.findAll(classQueryParam);

            classList.forEach(clazz -> {
                if (clazz.getEndDate().isBefore(LocalDate.now()) ) {
                    clazz.setStatus("已结束");
                } else {
                    clazz.setStatus("进行中");
                }
//                log.info("修改日期了我抄{}", clazz);

            });

            //3. 解析查询结果, 并封装
            Page<Clazz> p = (Page<Clazz>) classList;


            return new pageReturn<>((int) p.getTotal(), p.getResult());

        } catch (Exception e){
            System.out.println(e);
            return null;
        }

    }

    @Override
    public Object addOne(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        return classMapper.addOne(clazz);
    }

    @Override
    public Clazz getOneClassById(Integer id) {
        return classMapper.getOneClassById(id);
    }

    @Override
    public void updateOne(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        classMapper.updateOne(clazz);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOne(Integer id) {
        log.info("现在开始检查能否删掉班级");
        if(studentMapper.getStudentByClazzId(id).isEmpty()){
            classMapper.deleteOne(id);
            return true;
        }
        return false;
    }

    @Override
    public List<Clazz> getAllClassName() {
        return classMapper.getAllClassName();
    }
}
